## Russin.nu provides this API for non-commercial usage and only if you link it back.
## - Needed argument is title and optional is year.

module Shin
  module Reviews
    class Russin
      
      def new
        self
      end
      
      def find(h = {})
        # Search can either have title and year or only title
        if h[:year] != ""
          response = Base.get('http://www.russin.nu/api.php?soktitel='+URI.encode(h[:title])+"&year="+h[:year].to_s)
        elsif h[:title] != ""
          response = Base.get('http://www.russin.nu/api.php?soktitel='+URI.encode(h[:title]))
        else
          raise MissingArgument, "You are missing the argument 'title' which is required to use this source."
        end
       
        # Raise error if it didn't have a correct http code.
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Data, it can be multiple reviews for a single movie from different reviewers
        doc = Nokogiri::XML(response.body)
          
        doc.remove_namespaces!
        data = []
        doc.xpath("//data/russinrecension").each do |review|
          movie_title, movie_year = review.xpath('./filmtitel').text.split(", ")
          title = review.xpath('./rubrik').text
          rating = review.xpath('./betyg').text
          url = review.xpath('./url').text
          
          data << {name: movie_title, year: movie_year.to_i, title: title, rating: rating.to_i, url: url, votes: nil}
        end
        
        data.to_hashugar
      end
      
      class MissingArgument  < StandardError; end
      class HTTPError        < StandardError; end
    end
  end
end